import 'package:shared_preferences/shared_preferences.dart';
import '../models/comic_login_model.dart';
import '../models/comic_user_model.dart';
import 'http_helper.dart';

class UserManager {
  static const String _tokenKey = 'token';
  static const String _tokenTypeKey = 'tokenType';
  static const String _refreshTokenKey = 'refreshToken';
  static const String _expiredKey = 'expired';
  static const String _refreshExpiredKey = 'refreshExpired';

  // 保存登录信息
  static Future<void> saveLoginInfo(LoginTokenModel loginInfo) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_tokenKey, loginInfo.token ?? '');
    await prefs.setString(_tokenTypeKey, loginInfo.tokenType ?? '');
    await prefs.setString(_refreshTokenKey, loginInfo.refreshToken ?? '');
    await prefs.setString(_expiredKey, loginInfo.expired ?? '');
    await prefs.setString(_refreshExpiredKey, loginInfo.refreshExpired ?? '');
  }

  // 获取登录信息
  static Future<LoginTokenModel?> getLoginInfo() async {
    final prefs = await SharedPreferences.getInstance();
    final token = prefs.getString(_tokenKey);

    if (token == null || token.isEmpty) {
      return null;
    }

    return LoginTokenModel(
      token: token,
      tokenType: prefs.getString(_tokenTypeKey),
      refreshToken: prefs.getString(_refreshTokenKey),
      expired: prefs.getString(_expiredKey),
      refreshExpired: prefs.getString(_refreshExpiredKey),
    );
  }

  // 检查是否已登录
  static Future<bool> isLoggedIn() async {
    final loginInfo = await getLoginInfo();
    if (loginInfo == null ||
        loginInfo.token == null ||
        loginInfo.token!.isEmpty) {
      return false;
    }

    // 检查token是否过期（如果有过期时间）
    if (loginInfo.expired != null && loginInfo.expired!.isNotEmpty) {
      try {
        final expiredTime = DateTime.parse(loginInfo.expired!);
        if (DateTime.now().isAfter(expiredTime)) {
          await clearLoginInfo(); // 清除过期的登录信息
          return false;
        }
      } catch (e) {
        print('解析过期时间失败: $e');
      }
    }

    return true;
  }

  // 获取当前token
  static Future<String?> getCurrentToken() async {
    final loginInfo = await getLoginInfo();
    if (loginInfo?.token?.isEmpty == true || loginInfo == null) {
      final prefs = await SharedPreferences.getInstance();
      final token = prefs.getString(_tokenKey);

      if (token == null || token.isEmpty) {
        return "";
      } else {
        return token;
      }
    } else {
      return loginInfo.token;
    }
  }

  // 清除登录信息
  static Future<void> clearLoginInfo() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_tokenKey);
    await prefs.remove(_tokenTypeKey);
    await prefs.remove(_refreshTokenKey);
    await prefs.remove(_expiredKey);
    await prefs.remove(_refreshExpiredKey);
  }

  static Future<UserData?> getUserInfo() async {
    print("获取用户信息");
    try {
      // 首先检查是否已登录
      final isLoggedIn = await UserManager.isLoggedIn();
      if (!isLoggedIn) {
        return null;
      }

      // 发送请求获取用户信息
      final userResponse = await HttpUtil().getModel(
        'ComicMember/GetUserInfo',
        fromJson: (json) => UserData.fromJson(json as Map<String, dynamic>),
      );
      print("userResponse ${userResponse?.result?.nickname}");

      if (userResponse?.status == 200 && userResponse?.result != null) {
        return userResponse?.result;
      } else {
        return null;
      }
    } catch (e) {
      print('获取用户信息失败: $e');
      return null;
    }
  }

  static Future<void> saveToken(String token) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_tokenKey, token);

    // 同时更新loginInfo中的token
    final loginInfo = await getLoginInfo();
    if (loginInfo != null) {
      loginInfo.token = token;
      await saveLoginInfo(loginInfo);
    }
  }
}
